package cn.unknowpupil.init.service.system.impl;


import cn.unknowpupil.init.domain.system.SysJobLog;
import cn.unknowpupil.init.mapper.system.SysJobLogMapper;
import cn.unknowpupil.init.service.system.ISysJobLogService;
import cn.unknowpupil.init.utils.strings.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created at 2020-11-06 by  w10g <br>
 * Initialize SysJobLog  ... <br>
 * 定时任务调度日志表 核心业务处理实现类
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Service
public class SysJobLogServiceImpl extends ServiceImpl<SysJobLogMapper, SysJobLog> implements ISysJobLogService {


    @Override
    public IPage<SysJobLog> page(int current, int size, SysJobLog sysJobLog) {
        IPage<SysJobLog> page = new Page<>(current, size);
        LambdaQueryWrapper<SysJobLog> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(sysJobLog.getJobName())) {
            wrapper.like(SysJobLog::getJobName, sysJobLog.getJobName());
        }
        if (StringUtils.isNotBlank(sysJobLog.getJobGroup())) {
            wrapper.eq(SysJobLog::getJobGroup, sysJobLog.getJobGroup());
        }
        if (StringUtils.isNotBlank(sysJobLog.getStatus())) {
            wrapper.like(SysJobLog::getStatus, sysJobLog.getStatus());
        }
        if (StringUtils.isNotBlank(sysJobLog.getInvokeTarget())) {
            wrapper.like(SysJobLog::getInvokeTarget, sysJobLog.getInvokeTarget());
        }
        wrapper.apply(StringUtils.isNotBlank(sysJobLog.getBeginTime()),
                "date_format (create_time,'%Y-%m-%d') >= date_format('" + sysJobLog.getBeginTime() + "','%Y-%m-%d')");

        wrapper.apply(StringUtils.isNotBlank(sysJobLog.getEndTime()),
                "date_format (create_time,'%Y-%m-%d') <= date_format('" + sysJobLog.getEndTime() + "','%Y-%m-%d')");

        wrapper.orderByDesc(SysJobLog::getId);
        return super.page(page, wrapper);
    }



    /**
     * 新增任务日志
     *
     * @param jobLog 调度日志信息
     */
    @Override
    public boolean addJobLog(SysJobLog jobLog) {
        return save(jobLog);
    }

    /**
     * 批量删除调度日志信息
     *
     * @param logIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    public boolean deleteJobLogByIds(Long[] logIds) {
        List<Long> collect = Stream.of(logIds).collect(Collectors.toList());
        return removeByIds(collect);
    }


    /**
     * 清空任务日志
     */
    @Override
    public void cleanJobLog() {
        baseMapper.delete(null);
    }
}
